package com.kele.modbus.handler;

import com.kele.clinet.DeviceComponent;
import com.kele.clinet.DeviceConfig;
import com.kele.message.response.read.ReadHoldingRegistersResponseFrame;
import com.kele.store.DeviceConfigStorage;
import com.kele.type.DataType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.SocketAddress;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 读取保持寄存器应答帧处理器
 */
public class ReadHoldingRegistersResponseFrameHandler extends SimpleChannelInboundHandler<ReadHoldingRegistersResponseFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ReadHoldingRegistersResponseFrame msg) throws Exception {
        SocketAddress socketAddress = ctx.channel().localAddress();
        DeviceConfig deviceConfig = DeviceConfigStorage.get(socketAddress);
        if (Objects.isNull(deviceConfig)){
            return;
        }
        List<DeviceComponent> componentList = deviceConfig.getComponentList();

        // 拿到所有的传感器
        List<DeviceComponent> sensorList = componentList.stream()
                .filter(c -> Objects.equals(c.getType(), DeviceComponent.Type.SENSOR))
                .filter(c -> Objects.equals(c.getAddress(), msg.getAddressCode()))
                .filter(c -> Objects.equals(c.getFunction(), msg.getFunctionCode()))
                .collect(Collectors.toList());

        // 拿到所有寄存器信息
        List<DeviceComponent.Item> itemList = sensorList.stream()
                .map(DeviceComponent::getItemList)
                .flatMap(List::stream)
                .collect(Collectors.toList());

        ByteBuf content = msg.getContent();

        for (DeviceComponent.Item item : itemList) {
            int index = item.getIndex();
            // 一个寄存器返回两个字节
            String result = DataType.values()[item.getDataType()].get(content, index * 2);

            System.out.println(index + item.getName() + "-->" + result);
        }

        msg.release();
    }
}
